<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('回答列表')" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: bootstrap-select-css"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: jquery-smartwizard-css"/>
    <link th:href="@{/ajax/libs/layui/layui.css}" rel="stylesheet"/>
    <link href="//unpkg.com/layui@2.8.0/dist/css/layui.css" rel="stylesheet">

    <style>
        .qustitle{
            text-align: left;
        }
        .quespan{
            color: #00687D;
        }
        .white-bg{
            padding: 32px !important;
        }

    </style>
</head>
<body class="white-bg">
    <form class="form-horizontal m" id="form-hos-edit" th:object="${question}">
        <div class="form-group" >
            <input name="id" th:field="*{id}" type="hidden">
            <div class=" qustitle" style="font-size: 16px"><span class="quespan">问题:</span>[[*{questionTitle}]]</div>
        </div>
    </form>

    <div class="layui-tab" lay-filter="test-handle" lay-allowclose="true">
        <div class="layui-btn-container">
            <button class="layui-btn" lay-on="tabAdd">+ 新增回答</button>
        </div>
        <ul class="layui-tab-title" id="top_menu">
            <li class="layui-this" th:each="temp,iterStat : ${answers}" lay-id="8">
                回答 [[${iterStat.count}]]
            </li>
        </ul>

        <div class="layui-tab-content">
            <div class="layui-tab-item " th:each="temp : ${answers}">
                <input type="hidden" class="form-control" name="answerContent">
                <div class="summernote" th:id=${temp.id} th:utext= ${temp.answerContent}></div>
            </div>
        </div>
    </div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: summernote-js" />
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: select2-js"/>
<th:block th:include="include :: bootstrap-select-js"/>
<script src="//unpkg.com/layui@2.8.0/dist/layui.js"></script>

    <script th:inline="javascript">

        var placeholder = $(".summernote").attr("placeholder")

        var prefix = ctx + "yibanlv/answer";

        /*提交时所有的id*/
        var idList = [];

        /*返回参数集合*/
        var params = [];

        /*layui的方法*/
        layui.use(function(){

            /*编辑框全屏*/
            parent.$('body').find('.layui-layer-max').click()

            if([[${answers}]] == null){
                window.addtable('test-handle', {
                    title: '回答1',
                    content: '8',
                    id: new Date().getTime()
                })
            }

            /*初始化点击第一个选项卡*/
            layui.element.tabChange('test-handle', "8");

            /*初始化调用*/
            layer.ready(function(){

                /*所有的id填进idList*/
                [[${answers}]].forEach(answer=>(
                    idList.push(answer.id)
                ))

                /*浏览量*/
                var question = {}
                var key = 'id'
                var id = $('#id').val()
                question[key] = id
                    $.ajax({
                        url: '/yibanlv/question/browse',
                        type: 'POST',
                        async: false,
                        data: question,
                        success: function (data) {
                            console.log('浏览量+1')
                        }
                    })
                })
            });

            var element = layui.element;
            var util = layui.util;
            // 普通事件
            util.on('lay-on', {

                tabAdd: function(){
                    // 新增一个 tab 项
                    var count = $(".layui-tab-title li").length + 1;
                    window.addtable('test-handle', {
                        title: '回答'+ count,
                        content: count + 9999999,
                        id: new Date().getTime()
                    })
                    if(count == 1){
                        $("#top_menu li:first").attr("lay-id","1684461945054")

                        layui.element.tabChange('test-handle', "1684461945054");
                    }
                },

                tabDelete: function(othis){
                    // 删掉指定 tab 项
                    element.tabDelete('test-handle', '44');
                    othis.addClass('layui-btn-disabled');
                },

                tabChange: function(){
                    // 切换到指定 tab 项
                    element.tabChange('test-handle', '8');
                },

            });


        //外部Tab新增
        addtable = function(filter, options){
                var TITLE = '.layui-tab-title'
                    ,tabElem = $('.layui-tab[lay-filter='+ filter +']')
                    ,titElem = tabElem.children(TITLE)
                    ,barElem = titElem.children('.layui-tab-bar')
                    ,contElem = tabElem.children('.layui-tab-content')
                    ,call = {
                    //Tab 点击
                    tabClick: function(e, index, liElem, options){
                        options = options || {};
                        var othis = liElem || $(this)
                            ,index = index || othis.parent().children('li').index(othis)
                            ,parents = options.headerElem ? othis.parent() : othis.parents('.layui-tab').eq(0)
                            ,item = options.bodyElem ? $(options.bodyElem) : parents.children('.layui-tab-content').children('.layui-tab-item')
                            ,elemA = othis.find('a')
                            ,isJump = elemA.attr('href') !== 'javascript:;' && elemA.attr('target') === '_blank' //是否存在跳转
                            ,unselect = typeof othis.attr('lay-unselect') === 'string' //是否禁用选中
                            ,filter = parents.attr('lay-filter');

                        //执行切换
                        if(!(isJump || unselect)){
                            othis.addClass('layui-this').siblings().removeClass('layui-this');
                            item.eq(index).addClass('layui-show').siblings().removeClass('layui-show');
                        }

                        layui.event.call(this, 'element', 'tab('+ filter +')', {
                            elem: parents
                            ,index: index
                        });
                    }

                    //Tab删除
                    ,tabDelete: function(e, othis){
                        var li = othis || $(this).parent(), index = li.index()
                            ,parents = li.parents('.layui-tab').eq(0)
                            ,item = parents.children('.layui-tab-content').children('.layui-tab-item')
                            ,filter = parents.attr('lay-filter');

                        if(li.hasClass('layui-this')){
                            if(li.next()[0]){
                                call.tabClick.call(li.next()[0], null, index + 1);
                            } else if(li.prev()[0]){
                                call.tabClick.call(li.prev()[0], null, index - 1);
                            }
                        }

                        li.remove();
                        item.eq(index).remove();
                        setTimeout(function(){
                            call.tabAuto();
                        }, 50);

                        layui.event.call(this, 'element', 'tabDelete('+ filter +')', {
                            elem: parents
                            ,index: index
                        });
                    }

                    //Tab自适应
                    ,tabAuto: function(){
                        var SCROLL = 'layui-tab-scroll', MORE = 'layui-tab-more', BAR = 'layui-tab-bar'
                            ,CLOSE = 'layui-tab-close', that = this;

                        $('.layui-tab').each(function(){
                            var othis = $(this)
                                ,title = othis.children('.layui-tab-title')
                                ,item = othis.children('.layui-tab-content').children('.layui-tab-item')
                                ,STOPE = 'lay-stope="tabmore"'
                                ,span = $('<span class="layui-unselect layui-tab-bar" '+ STOPE +'><i '+ STOPE +' class="layui-icon">&#xe61a;</i></span>');

                            if(that === window && device.ie != 8){
                                call.hideTabMore(true)
                            }

                            //允许关闭
                            if(othis.attr('lay-allowClose')){
                                title.find('li').each(function(){
                                    var li = $(this);
                                    if(!li.find('.'+CLOSE)[0]){
                                        var close = $('<i class="layui-icon layui-icon-close layui-unselect '+ CLOSE +'"></i>');
                                        close.on('click', call.tabDelete);
                                        li.append(close);
                                    }
                                });
                            }

                            if(typeof othis.attr('lay-unauto') === 'string') return;

                            //响应式
                            if(title.prop('scrollWidth') > title.outerWidth()+1){
                                if(title.find('.'+BAR)[0]) return;
                                title.append(span);
                                othis.attr('overflow', '');
                                span.on('click', function(e){
                                    title[this.title ? 'removeClass' : 'addClass'](MORE);
                                    this.title = this.title ? '' : '收缩';
                                });
                            } else {
                                title.find('.'+BAR).remove();
                                othis.removeAttr('overflow');
                            }
                        });
                    }
                    //隐藏更多Tab
                    ,hideTabMore: function(e){
                        var tsbTitle = $('.layui-tab-title');
                        if(e === true || $(e.target).attr('lay-stope') !== 'tabmore'){
                            tsbTitle.removeClass('layui-tab-more');
                            tsbTitle.find('.layui-tab-bar').attr('title','');
                        }
                    }

                    //点击菜单 - a标签触发
                    ,clickThis: function(){
                        var othis = $(this)
                            ,parents = othis.parents(NAV_ELEM)
                            ,filter = parents.attr('lay-filter')
                            ,parent = othis.parent()
                            ,child = othis.siblings('.'+NAV_CHILD)
                            ,unselect = typeof parent.attr('lay-unselect') === 'string'; //是否禁用选中

                        if(!(othis.attr('href') !== 'javascript:;' && othis.attr('target') === '_blank') && !unselect){
                            if(!child[0]){
                                parents.find('.'+THIS).removeClass(THIS);
                                parent.addClass(THIS);
                            }
                        }

                        //如果是垂直菜单
                        if(parents.hasClass(NAV_TREE)){
                            child.removeClass(NAV_ANIM);

                            //如果有子菜单，则展开
                            if(child[0]){
                                parent[child.css('display') === 'none' ? 'addClass': 'removeClass'](NAV_ITEM+'ed');
                                if(parents.attr('lay-shrink') === 'all'){
                                    parent.siblings().removeClass(NAV_ITEM + 'ed');
                                }
                            }
                        }

                        layui.event.call(this, 'element', 'nav('+ filter +')', othis);
                    }
                    //折叠面板
                    ,collapse: function(){
                        var othis = $(this), icon = othis.find('.layui-colla-icon')
                            ,elemCont = othis.siblings('.layui-colla-content')
                            ,parents = othis.parents('.layui-collapse').eq(0)
                            ,filter = parents.attr('lay-filter')
                            ,isNone = elemCont.css('display') === 'none';

                        //是否手风琴
                        if(typeof parents.attr('lay-accordion') === 'string'){
                            var show = parents.children('.layui-colla-item').children('.'+SHOW);
                            show.siblings('.layui-colla-title').children('.layui-colla-icon').html('&#xe602;');
                            show.removeClass(SHOW);
                        }

                        elemCont[isNone ? 'addClass' : 'removeClass'](SHOW);
                        icon.html(isNone ? '&#xe61a;' : '&#xe602;');

                        layui.event.call(this, 'element', 'collapse('+ filter +')', {
                            title: othis
                            ,content: elemCont
                            ,show: isNone
                        });
                    }
                }
                    ,li = '<li'+ function(){
                    var layAttr = [];
                    layui.each(options, function(key, value){
                        if(/^(title|content)$/.test(key)) return;
                        layAttr.push('lay-'+ key +'="'+ value +'"');
                    });
                    if(layAttr.length > 0) layAttr.unshift(''); //向前插，预留空格
                    return layAttr.join(' ');
                }() +'>'+ (options.title || 'unnaming') +'</li>';

                barElem[0] ? barElem.before(li) : titElem.append(li);
                contElem.append('<div class="layui-tab-item"><input type="hidden" id="box" name="answerContent"><div class="summernote" id="' + (options.content || '') + '" style="display: none;"></div></div>');
                call.hideTabMore(true);
                call.tabAuto();
                idList.push(options.content)
                summernoteByClass("summernote")
                return this
            }

        /*富文本*/
        $(function () {
            $('.summernote').each(function (i) {
                $('#' + this.id).summernote({
                    lang: 'zh-CN',
                    dialogsInBody: true,
                    placeholder: placeholder,
                    callbacks: {
                        onChange: function (contents, $edittable) {
                            $("input[name='" + this.id + "']").val(contents);
                        },
                        onImageUpload: function (files) {
                            var obj = this;
                            var data = new FormData();
                            data.append("file", files[0]);
                            $.ajax({
                                type: "post",
                                url: ctx + "common/upload",
                                data: data,
                                cache: false,
                                contentType: false,
                                processData: false,
                                dataType: 'json',
                                success: function (result) {
                                    if (result.code == web_status.SUCCESS) {
                                        $('#' + obj.id).summernote('insertImage', result.url);
                                    } else {
                                        $.modal.alertError(result.msg);
                                    }
                                },
                                error: function (error) {
                                    $.modal.alertWarning("图片上传失败。");
                                }
                            });
                        }
                    }
                });
                var content = $("input[name='" + this.id + "']").val();
                $('#' + this.id).summernote('code', content);
            })
        });

        /*调用富文本*/
        function summernoteByClass(className) {
            $('.'+className).summernote({
                lang: 'zh-CN',
                dialogsInBody: true,
                callbacks: {
                    onChange: function(contents, $edittable) {
                        $("input[name='" + this.id + "']").val(contents);
                        if(this.id == "content")
                            $("textarea[name='noFormatContent']").val(getText(contents));
                    },
                    onImageUpload: function(files) {
                        var obj = this;
                        var data = new FormData();
                        data.append("file", files[0]);
                        $.ajax({
                            type: "post",
                            url: ctx + "common/upload",
                            data: data,
                            cache: false,
                            contentType: false,
                            processData: false,
                            dataType: 'json',
                            success: function(result) {
                                if (result.code == web_status.SUCCESS) {
                                    $('#' + obj.id).summernote('insertImage', result.fileName);
                                } else {
                                    $.modal.alertError(result.msg);
                                }
                            },
                            error: function(error) {
                                $.modal.alertWarning("图片上传失败。");
                            }
                        });
                    }
                }
            });
        }


        /*确定提交*/
        function submitHandler() {
            idList.forEach(id => {
            var answer = {}
            answer.id = id;
            answer.answerContent = getvalues(id);
            answer.questionid = [[${question.id}]];
            params.push(answer)
        })
            /*if ($.validate.form()) {
                $.operate.save(prefix + "/batchAddOrEdit", $('#form-hospital-add').serialize());
            }*/
            var data =JSON.stringify(params);
            console.log(data)
            $.ajax({
                url: '/yibanlv/answer/batchAddOrEdit',
                type: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=utf8'
                },
                async: false,
                data: data,
                success: function (data) {
                    $.modal.msgReload(data.msg);
                }
            })
        }

        /*获取到所有的富文本id*/
        function getvalues(id){
            id="#"+id;
            var str= $(id).summernote('code');
            return str
        }


    </script>
</body>
</html>
